<script setup lang="ts">
import axios from "axios";
import { ElMessage } from "element-plus";
import { onMounted, onUnmounted, ref } from "vue";
import { useRoute } from "vue-router";
import type { Category } from "../../types/Book";
import type { ResultContext } from "../../types/ResultContext";

const categoryList = ref<Category[]>([]);
const loading = ref(false);
const selectedCategory = ref<Category | null>(null);
const route = useRoute();

const emit = defineEmits(["select"]);

const handleClick = (item: Category | null) => {
  selectedCategory.value = item;
  emit("select", item); // 向父组件传递 item
};

// 从后端获取分类数据
onMounted(async () => {
  loading.value = true;
  try {
    const res = await axios.get<ResultContext<Category[]>>(
      "http://localhost:8080/api/categories",
    );
    categoryList.value = res.data.data;

    // 将 query 参数转换为 number
    const categoryIdFromQuery = Number(route.query.categoryId);

    // 如果 URL 里带了 categoryId，自动选中它
    const target = categoryList.value.find(
      item => item.id === categoryIdFromQuery,
    );
    if (target) {
      handleClick(target);
    } else {
      handleClick(null); // 默认传递空值
    }
  } catch (error) {
    if (error instanceof Error) {
      ElMessage.error(error.message);
    }
  } finally {
    loading.value = false;
  }
  const backToTopBtn = document.getElementById("backToTop");
  if (!backToTopBtn) return;

  const onScroll = () => {
    if (window.scrollY > 200) {
      backToTopBtn.style.display = "block";
    } else {
      backToTopBtn.style.display = "none";
    }
  };

  const onClick = (e: MouseEvent) => {
    e.preventDefault();
    window.scrollTo({
      top: 0,
      behavior: "smooth",
    });
  };

  window.addEventListener("scroll", onScroll);
  backToTopBtn.addEventListener("click", onClick);

  onUnmounted(() => {
    window.removeEventListener("scroll", onScroll);
    backToTopBtn.removeEventListener("click", onClick);
  });
});
</script>

<template>
  <div class="category-nav">
    <div class="nav-header">
      <h3 class="nav-title">图书分类</h3>
      <p class="nav-subtitle">选择感兴趣的分类</p>
    </div>

    <div class="nav-content">
      <div class="loading-state" v-if="loading">
        <div class="loading-spinner"></div>
        <span>加载分类中...</span>
      </div>

      <div class="nav-list" v-else>
        <div
          class="nav-item"
          @click="handleClick(null)"
          :class="{ active: selectedCategory === null }"
        >
          <div class="category-card">
            <span class="category-name">全部</span>
            <div class="category-indicator"></div>
          </div>
        </div>

        <div
          class="nav-item"
          v-for="(item, index) in categoryList"
          :key="index"
          @click="handleClick(item)"
          :class="{ active: selectedCategory?.id === item.id }"
        >
          <div class="category-card">
            <span class="category-name">{{ item.name }}</span>
            <div class="category-indicator"></div>
          </div>
        </div>
      </div>
    </div>
    <a href="#" class="back-to-top" id="backToTop" style="display: none"
      >回到顶部</a
    >
  </div>
</template>

<style scoped>
.category-nav {
  width: 280px;
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  position: sticky;
  top: 80px; /* 为顶部导航栏留出空间 */
  height: fit-content;
  max-height: calc(100vh - 104px); /* 减去top值和底部边距 */
  z-index: 10; /* 确保在一般内容之上，但在对话框之下 */
}

.nav-header {
  padding: 24px 20px 16px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  text-align: center;
}

.nav-title {
  margin: 0 0 4px 0;
  font-size: 18px;
  font-weight: 600;
}

.nav-subtitle {
  margin: 0;
  font-size: 14px;
  opacity: 0.9;
}

.nav-content {
  padding: 16px 0;
  max-height: calc(
    100vh - 200px
  ); /* 调整最大高度，减去头部和顶部导航栏的空间 */
  overflow-y: auto;
}

.loading-state,
.error-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 32px 20px;
  color: #666;
}

.loading-spinner {
  width: 24px;
  height: 24px;
  border: 2px solid #f0f0f0;
  border-top: 2px solid #667eea;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 12px;
}

.error-icon {
  font-size: 32px;
  margin-bottom: 8px;
}

.error-state p {
  margin: 0;
  font-size: 14px;
  text-align: center;
}

.nav-list {
  padding: 0 12px;
}

.nav-item {
  margin-bottom: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.nav-item:last-child {
  margin-bottom: 0;
}

.category-card {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  border-radius: 12px;
  background: #f8f9fa;
  border: 2px solid transparent;
  transition: all 0.2s ease;
  position: relative;
}

.nav-item:hover .category-card {
  background: #e3f2fd;
  border-color: #bbdefb;
  transform: translateX(4px);
}

.nav-item.active .category-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-color: #667eea;
  color: white;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.category-name {
  font-size: 14px;
  font-weight: 500;
  flex: 1;
}

.category-indicator {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background: currentColor;
  opacity: 0.6;
  transition: all 0.2s ease;
}

.nav-item.active .category-indicator {
  opacity: 1;
  transform: scale(1.2);
}

/* 滚动条样式 */
.nav-content::-webkit-scrollbar {
  width: 6px;
}

.nav-content::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.nav-content::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.nav-content::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .category-nav {
    width: 240px;
  }

  .nav-header {
    padding: 20px 16px 12px;
  }

  .nav-title {
    font-size: 16px;
  }

  .nav-subtitle {
    font-size: 13px;
  }
}

@media (max-width: 768px) {
  .category-nav {
    position: fixed;
    left: -280px;
    top: 0;
    bottom: 0;
    width: 280px;
    z-index: 999;
    transition: left 0.3s ease;
    max-height: 100vh;
    border-radius: 0;
  }

  .category-nav.mobile-open {
    left: 0;
  }
}
.back-to-top {
  position: fixed;
  bottom: 40px;
  right: 40px;
  background: #409eff;
  color: white;
  padding: 10px 16px;
  border-radius: 24px;
  font-weight: 600;
  font-size: 14px;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
  cursor: pointer;
  transition:
    background-color 0.3s ease,
    box-shadow 0.3s ease;
  user-select: none;
  text-decoration: none;
  z-index: 1000;
}

.back-to-top:hover {
  background: #53c0ff;
  box-shadow: 0 6px 20px rgba(64, 158, 255, 0.5);
}
</style>
